package com.fuyun.rpc.common.trace;

import java.util.UUID;

/**
 * 链路追踪上下文
 */
public class TraceContext {

	/**
	 * 全局唯一的追踪ID
	 */
	private String traceId;

	/**
	 * 当前跨度ID
	 */
	private String spanId;

	/**
	 * 父跨度ID
	 */
	private String parentSpanId;

	/**
	 * 服务名称
	 */
	private String serviceName;

	/**
	 * 方法名称
	 */
	private String methodName;

	/**
	 * 开始时间戳
	 */
	private long startTime;

	/**
	 * 结束时间戳
	 */
	private long endTime;

	public TraceContext() {
		this.traceId = UUID.randomUUID()
			.toString()
			.replace("-", "");
		this.spanId = UUID.randomUUID()
			.toString()
			.replace("-", "")
			.substring(0, 16);
		this.startTime = System.currentTimeMillis();
	}

	public TraceContext(String traceId, String parentSpanId) {
		this.traceId = traceId;
		this.parentSpanId = parentSpanId;
		this.spanId = UUID.randomUUID()
			.toString()
			.replace("-", "")
			.substring(0, 16);
		this.startTime = System.currentTimeMillis();
	}

	// Getters and Setters

	public String getTraceId() {
		return traceId;
	}

	public void setTraceId(String traceId) {
		this.traceId = traceId;
	}

	public String getSpanId() {
		return spanId;
	}

	public void setSpanId(String spanId) {
		this.spanId = spanId;
	}

	public String getParentSpanId() {
		return parentSpanId;
	}

	public void setParentSpanId(String parentSpanId) {
		this.parentSpanId = parentSpanId;
	}

	public String getServiceName() {
		return serviceName;
	}

	public void setServiceName(String serviceName) {
		this.serviceName = serviceName;
	}

	public String getMethodName() {
		return methodName;
	}

	public void setMethodName(String methodName) {
		this.methodName = methodName;
	}

	public long getStartTime() {
		return startTime;
	}

	public void setStartTime(long startTime) {
		this.startTime = startTime;
	}

	public long getEndTime() {
		return endTime;
	}

	public void setEndTime(long endTime) {
		this.endTime = endTime;
	}

	public long getDuration() {
		if (endTime > 0) {
			return endTime - startTime;
		}
		return System.currentTimeMillis() - startTime;
	}

	@Override
	public String toString() {
		return "TraceContext{" + "traceId='" + traceId + '\'' + ", spanId='" + spanId + '\'' + ", parentSpanId='" + parentSpanId + '\'' + ", serviceName='" + serviceName + '\'' + ", methodName='" + methodName + '\'' + ", duration=" + getDuration() + "ms" + '}';
	}
}